package com.webull.information.center.carwler.task.handler;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.webull.cms.client.model.YgTickerMap;
import com.webull.cms.client.service.YgTickerMapService;
import com.webull.information.center.carwler.common.model.NewsInformation;
import com.webull.information.center.carwler.common.model.StockConfig;
import com.webull.information.center.carwler.common.model.StockTitle;
import com.webull.information.center.carwler.common.util.jsoup.HttpJsoupClient;
import com.webull.information.center.carwler.common.util.news.CNBCNewsListUitl;
import com.webull.information.center.carwler.common.util.news.CNBCNewsListUitl.CNBCItem;
import com.webull.information.center.carwler.task.support.StockConfigSupport;
import com.webull.information.center.carwler.task.support.TikcerNewsProcessor;
import com.webull.information.center.common.constants.Constants;
import com.webull.information.center.common.constants.UrlConstants;
import com.webull.information.client.model.News;
import com.webull.information.client.model.parm.NewsRelType;

/**
 * 美国CNBC
 *
 * @author shimingjun
 * @version 1.0
 * @date 2017年3月2日 下午3:28:48
 * @since JDK 1.8
 */
@Component
public class StockCNBCNewsHandler {

    protected final Logger logger = LogManager.getLogger(getClass());
    private static String cnbc_lang = Constants.lang_en;// 新浪语言版本
    private @Autowired
    CNBCNewsListUitl cNBCNewsListUitl;
    private @Autowired
    StockConfigSupport stockConfigSupport;
    private @Autowired
    YgTickerMapService ygTickerMapService;
    private @Autowired
    TikcerNewsProcessor tikcerNewsProcessor;

    private String googleSymbol(Integer tickerId) {
        YgTickerMap param = new YgTickerMap();
        param.setTickerId(tickerId);
        return Optional.ofNullable(ygTickerMapService.search(param))//
                .filter(v -> v.size() >= 1).map(v -> v.get(0).getSymbol()).orElse(null);
    }



	public void handlerByStockTitle4CNBC(StockTitle stockTitle) {
        String cnbcSymbol = Optional.ofNullable(googleSymbol(stockTitle.getTickerId())).orElse(stockTitle.getSymbol());
//"cnbc_en"
		String colSource = stockTitle.getCfgSource();
        StockConfig stockConfig = stockConfigSupport.getStockConfig(stockTitle, colSource, cnbc_lang);
        String newsProfile = getCNBCProfileUrl(stockTitle.getRegionId(), cnbcSymbol);
        processCNBCList(stockConfig, stockTitle, newsProfile);
    }

    private void processCNBCList(StockConfig stockConfig, StockTitle stockTitle, String newsProfile) {
        try {
            List<Date> times = new ArrayList<>();
            Date lastPush = stockConfig.getCollectTime();
            /**
             * 获取标的物新闻首页列表
             */
            List<CNBCItem> newsList = cNBCNewsListUitl.parseNewsList(newsProfile);
            //
            entrie:
            for (int i = 0; newsList != null && i < newsList.size(); i++) {
                try {
                    CNBCItem item = newsList.get(i);
                    Date push = item.getNewsTime();
                    if (push == null) {
                        logger.warn("-processSinaList stockTitle:{}, url:{} CNBCItem:{}, push can't be parse!!",
                                stockTitle, newsProfile, item);
                        continue entrie;
                    }

                    if (lastPush == null || DateUtils.isSameDay(push, new Date()) || push.after(lastPush)) {
                        times.add(push);
                        processCNBCNews(stockTitle, item);
                    }
                } catch (Exception e) {
                    logger.warn(e);
                    break entrie;
                }
            }

            if (!times.isEmpty()) {
                tikcerNewsProcessor.updateStockConfig(stockConfig, times);
                stockConfigSupport.updateById(stockConfig);
            }

        } catch (Exception e) {
            stockConfig.setCollectNumber(-99);
            stockConfigSupport.updateById(stockConfig);
            logger.error("processRss(Date lastPush, StockTitle stockTitle, String compFinanceRss)", e);
        }
    }

    private void processCNBCNews(StockTitle stockTitle, CNBCItem item) throws Exception {
        String title = item.getTitle();
        String link = item.getLink();
        // SyndContent description = entry.getDescription();
        NewsInformation info = new NewsInformation();// produce(doc);
        info.setCollectSource(News.CollectSource.Cnbc);
        info.setSiteType(News.SiteType.PIRORIT);
        info.setTitle(title);
        info.setRegionId(stockTitle.getRegionId());
        info.setSummary(item.getSummery());
        info.setNewsTime(item.getNewsTime());
        info.setUrl(link);
        info.addMainPic(item.getMainPic());
        info.setMainProxy(true);
        info.setLanguage(cnbc_lang);

        info.setSourceName(item.getSource());
        String md5 = HttpJsoupClient.finishingMd5Url(link);
        info.setUrlMd5(md5);

        tikcerNewsProcessor.bindTargetNewsRecord(info, stockTitle.getTickerId(), NewsRelType.ticker);
    }

    /**
     * 转换成CNBC的新闻列表url
     * <pre>
     * 目前只支持美股
     * </pre>
     *
     * @param regionId
     * @param cnbcSymbol
     * @return
     */
    private String getCNBCProfileUrl(Integer regionId, String cnbcSymbol) {
        if (Integer.valueOf(6).equals(regionId)) //
            return StringUtils.replaceOnce(UrlConstants.cnbcNewsUnitUrl, "{0}", cnbcSymbol);
        return null;
    }

}
